//
//  WBUserAccount.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/7.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit

//归档和解档路径
private let SaveUserAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")

class WBUserAccount: NSObject,NSCoding {
    // 访问令牌
    var access_token: String?
    // 令牌过期秒数
    var expires_in: Int = 0{
        didSet {
            expiresDate = Date().addingTimeInterval(TimeInterval(expires_in))
        }
    }
    // 用户名
    var name: String?
    // 过期时间
    var expiresDate: Date?
    // 用户ID 
    var uid: Int64 = 0
    // 头像地址
    var avatar_large: String?
    
    init(dict: [String:Any]) {
        
        super.init()
        setValuesForKeys(dict)
        
    }
    // 防止字段不匹配
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
        // 空实现
    }
    
    // MARK: --归档和解档
    func encode(with aCoder: NSCoder) {
        
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")

    }
    // 解档
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
        
    }
    // 保存用户对象
    func saveUserAccount() {
        
        NSKeyedArchiver.archiveRootObject(self, toFile:SaveUserAccountPath)
    }
    
    // 读取用户信息
    class func loadUserAccount() ->WBUserAccount? {
        
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: SaveUserAccountPath) as?WBUserAccount
        
        return userAccount
    }
    
}
